<template>
  <div class="blog-toc-container">
    <h2>目录</h2>
    <RightList :list="tocWidthSelect" @selected="handleSelect"/>
  </div>
</template>

<script>
import RightList from "./RightList";
import {debounce} from "@/utils";

export default {
  name: "BlogTOC",
  components: {
    RightList,
  },
  props: {
    toc: {
      type: Array,
    },

  },
  data() {
    return {
      activeAnchor: ""
    }
  },
  computed: {
    // 处理列表数据，添加 isSelect 属性
    tocWidthSelect() {
      const getToc = (toc = []) => {
        return toc.map(
            (item) => ({
              ...item,
              isSelect: item.anchor === this.activeAnchor,
              children: getToc(item.children)
            })
        );
      }
      return getToc(this.toc)
    },

    doms() {
      let domList = [];
      const add = (toc) => {
        for(let item of toc) {
          domList.push(document.getElementById(item.anchor));
          if(item.children && item.children.length) {
            add(item.children);
          }
        }
      }
      add(this.toc);
      return domList;
    },
  },
  methods: {
    handleSelect(item) {
      location.hash = item.anchor;
    },
    setSelect() {
      this.activeAnchor = "";
      let range = 200;
      for(let dom of this.doms) {
        if(!dom) continue;
        let top = dom.getBoundingClientRect().top;
        if(top >= 0 && top <= range) {
          // * 在规定范围内
          this.activeAnchor = dom.id;
          return;
        } else if (top > range)  {
          // * 在规定范围的下面
          return;
        } else {
          // * 在规定范围的上面
          this.activeAnchor = dom.id;
        }
      }
    }
  },
  created() {
    this.setSelectDebounce = debounce(this.setSelect, 50);
    this.$eventBus.$on("mainScroll", this.setSelectDebounce);
  },
  destroyed() {
    this.$eventBus.$off("mainScroll", this.setSelectDebounce);
  }
};
</script>

<style scoped lang="less">
.blog-toc-container {
  h2 {
    font-weight: bold;
    letter-spacing: 2px;
    font-size: 1em;
    margin: 0;
  }
}
</style>
